/*
  create hashmap with less memory less calc.
*/
#include <stdio.h>
#include <malloc.h>

#include "comm.h"
#include "hashmap.h"

BUCKET buckets[BUCKET_LEN];
extern BUCKET *cntbuckets[SEGNUM];  //为了简单，直接申请100个，线程不超过100 
 

int insert_key(int segno, unsigned int key, char *data){
	unsigned int idx = key % 0x000FFFFF;
        int count;
	BUCKET *bucket = buckets + idx;
	if (bucket->count == 0){
                count = __sync_add_and_fetch(&bucket->count, 1);
		bucket->key = key;
		bucket->data = data;
		return 0;
	}else{
		BUCKET *next = bucket;
		while (next){
			if (next->key == key){
				count = __sync_add_and_fetch(&next->count, 1);
                		if (NULL == cntbuckets[segno] || count > cntbuckets[segno]->count)
					cntbuckets[segno] = next;
				return 0;
			}
			next = next->next;
		}
		BUCKET* newbucket = (BUCKET*)malloc(sizeof(BUCKET));
		newbucket->key = key;
                newbucket->count = 1;
		newbucket->data = data;
		atomic_lock(&bucket->lock);
		newbucket->next = bucket->next;
		bucket->next = newbucket;
		atomic_unlock(&bucket->lock);
	}

   return 0;
}
